import React, { ComponentClass, createElement, FC, ReactNode, useEffect, useRef } from 'react';
import Sortable from 'sortablejs';

function Draggable<T>(props: {
    display: FC<T> | ComponentClass<T>;
    children?: ReactNode;
    options?: Sortable.Options;
    props?: T;
}) {
    const sortableRef = useRef<Sortable>();
    const wrapRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (wrapRef.current) {
            sortableRef.current = new Sortable(
                wrapRef.current,
                Object.assign(props.options)
            );
        }
    }, []);

    return createElement(props.display, {
        ...props.props,
        children: props.children,
        ref: wrapRef
    });
}

export default Draggable;
